<template>
	<view class="container">
		<view @click="openPopup()">
			<up-input :placeholder="placeholder" border="surround" v-model="_value"
				:customStyle="{ width: '83vw', pointerEvents: 'none' }"  readonly></up-input>
		</view>
		<up-picker :show="show" :columns="columns" :closeOnClickOverlay="true" @close="closePopup" @confirm="confirm"
			@cancel="show = false" keyName='name'></up-picker>
		<up-toast ref="uToastRef"></up-toast>
	</view>
</template>

<script>
import org from '@/apis/cloud/org.js'
import componentMinxins from '../ComponentMinxins'

export default {
	mixins: [componentMinxins],
	name: "SelectInput",
	props: {
		value: {
			type: String,
			default: null
		},
		itemIndex: {
			type: Number,
			default: 0
		},
		placeholder: {
			type: String,
			default: '请输入内容'
		},
		options: {
			type: Array,
			default: () => {
				return []
			}
		},
		source: {
			type: Number,
			default: 1
		},
		sourceType: {
			type: Number,
			default: 1
		},
		format: {
			type: String,
			default: ''
		},
		title: {
			type: String,
			default: ''
    },
    titleItems:{
      type: String,
      default: null
    },
    field: {
      type: [String, Number],
      required: true
    },
    itemId: {
      type: String,
      required: true
    },
    ApplyDetailList: {
      type: Array,
      default: () => {
        return []
      }
    },
	},
	data() {
		return {
			show: false,
			columns: [],
			_value: '',
      Selesupplier:null,
		}
	},
  created() {
    uni.$on('Selesupplier', this.handleSelesupplier);
    uni.$on('requisitioner', this.handleSelesupplier);
    uni.$on('purchaser', this.handleSelesupplier);
    uni.$on('project', this.handleSelesupplier);
    uni.$on('contract', this.handleSelesupplier);
  },
  beforeDestroy() {
    uni.$off('Selesupplier', this.handleSelesupplier);
    uni.$off('requisitioner', this.handleSelesupplier);
    uni.$off('purchaser', this.handleSelesupplier);
    uni.$off('project', this.handleSelesupplier);
    uni.$off('contract', this.handleSelesupplier);
  },
  mounted() {
    const cached = uni.getStorageSync(this.itemId);
    if (cached) {
      this._value = cached;
    }

    let value = uni.getStorageSync('formData');
    let selectedOrg = JSON.parse(uni.getStorageSync('user')).user || JSON.parse(uni.getStorageSync('user'))
    let formItems = JSON.parse(value.formItems);
    formItems.forEach(item => {
      if (item.title == this.title) {
        uni.removeStorageSync(`${item.id}`);
        if(item.title == '组织'){
          this.$nextTick(()=>{
            this._value = selectedOrg.selectedOrg.name
            this.Selesupplier = selectedOrg.selectedOrg.id
            uni.setStorageSync(item.id, selectedOrg.selectedOrg.id);
          })
        }
      }
    })
		this.getList()
    this.setechodata()
	},
	watch: {
		_value: {
			handler(newValue) {
				let value = uni.getStorageSync('formData');
				let formItems = JSON.parse(value.formItems);
				formItems.forEach(item => {
					if (item.title == this.title) {
						item.value = newValue;
						uni.setStorageSync(item.id, this.Selesupplier);
            }else if(this.titleItems == item.title && item.title == this.titleItems){
              item.props.items.forEach(item =>{
                if (item.title == this.title) {
                  item.value = newValue;
                  uni.setStorageSync(item.id, this.Selesupplier);
                }
              })
					  }
				})
			}
		}
	},
	methods: {
    setechodata(){
      // 添加数据回显逻辑
      if (this.ApplyDetailList && this.ApplyDetailList.formData  && this.itemId)  {
        // 检查 formData 中是否存在当前 itemId 对应的字段 
        if (this.ApplyDetailList.formData.hasOwnProperty(this.itemId))  {
          // 获取对应的值
          const fieldValue = this.ApplyDetailList.formData[this.itemId]; 
          
          // 如果值是数组，取第一个元素（根据你的数据结构）
          if (Array.isArray(fieldValue)  && fieldValue.length  > 0) {
            this._value = fieldValue || []
          } else {
            // 直接赋值 
            this._value = fieldValue || '';
            this.Selesupplier = fieldValue || '';
          }
        }
      }
    },
    handleSelesupplier(data) {
      if (String(data.field) !== String(this.field)) return;
      this._value = data.name || data;
      delete data.field
      this.Selesupplier = data.id
    },
		getList() {
			if (this.source == 1) {
				this.columns = [this.options];
			} else {
				switch (this.sourceType) {
					case 1: //仓库
						org.getBrand({}).then(rsp => {
							let data = []
							msg.data.map(item => {
								data.push(item.brand_name)
							});
							this.columns[0] = data
						}).catch(err => {
							uni.$u.toast('仓库数据异常')
						})
						break;
					case 2: //收货人
						org.getContact({}).then(rsp => {
							this.columns = [rsp.data];
						}).catch(err => {
							uni.$u.toast('收货人数据异常')
						})
						break;
					case 3: //承运人
						org.getCarrier({}).then(rsp => {
							this.columns = [rsp.data];
						}).catch(err => {
							uni.$u.toast('承运人数据异常')
						})
						break;
					case 4: //供应商
						org.getSupply({

            }).then(rsp => {
							this.columns = [rsp.data];
						}).catch(err => {
							uni.$u.toast('供应商数据异常')
						})
						break;
					case 5: //项目
						org.getProject({}).then(rsp => {
							this.columns = [rsp.data];
						}).catch(err => {
							uni.$u.toast('项目数据异常')
						})
						break;
					case 6: //合同
						org.getContract({}).then(rsp => {
							this.columns = [rsp.data];
						}).catch(err => {
							uni.$u.toast('合同数据异常');
						})
						break;
					case 7: //组织
						// org.getOrganization({}).then(res => {
						// 	this.columns = [res.data];
						// }).catch(err => {
						// 	uni.$u.toast('组织数据异常');
						// });
						break;
					case 8: //试验区域
						org.getTestArea({}).then(rsp => {
							this.columns = [rsp.data];
						}).catch(err => {
							uni.$u.toast('试验区域数据异常')
						})
						break;
					case 9: //试验品种
						org.getTestBreed({}).then(rsp => {
							this.columns = [rsp.data];
						}).catch(err => {
							uni.$u.toast('试验品种数据异常')
						})
						break;
					case 10: //生产车间
						org.getWorkshop({}).then(rsp => {
							this.columns = [rsp.data];
						}).catch(err => {
							uni.$u.toast('生产车间数据异常')
						})
						break;
				}
			}
		},
		openPopup() {
      let value = uni.getStorageSync('formData');
      let formItems = JSON.parse(value.formItems);
      formItems.forEach(item => {
        if (item.title == this.title) {
          if(item.props.field == '241' || item.props.field == '226'){
            this.show = false
          }else if(item.props.field == '69'){
            uni.navigateTo({
              url: `/pages/apply/form/components/getSupplyDetail?type=4&materialType=0&org_id=0&name=供应商&field=${item.props.field}`
            });
          }else if(item.props.field == '70'){
            uni.navigateTo({
              url: `/pages/apply/form/components/getSupplyDetail?type=1&materialType=0&org_id=0&name=申购人&field=${item.props.field}`
            });
          }else if(item.props.field == '71'){
            uni.navigateTo({
              url: `/pages/apply/form/components/getSupplyDetail?type=34&materialType=0&org_id=0&name=采购员&field=${item.props.field}`
            });
          }else if(item.props.field == '242' || item.props.field == '227'){
            uni.navigateTo({
              url: `/pages/apply/form/components/getSupplyDetail?type=25&materialType=0&org_id=0&name=项目&field=${item.props.field}`
            });
          }
          else if(item.props.field == '228'){
            uni.navigateTo({
              url: `/pages/apply/form/components/getSupplyDetail?type=26&materialType=0&org_id=0&name=合同&field=${item.props.field}`
            });
          }
          else{
            this.show = true
          }



        }
      })

		},
		closePopup() {
			this.show = false;
		},
		confirm(val) {
			switch (this.sourceType) {
				case 1:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 2:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 3:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 4:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 5:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 6:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 7:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 8:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 9:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				case 10:
					this._value = val.value[0].name || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
					break;
				default:
					this._value = val.value[0] || val.value[0];
          this.Selesupplier = val.value[0].name || val.value[0];
			}
			this.show = false;
		}
	}
}
</script>

<style></style>
